//
//  NSString+Categories.m
//

#import "NSString+Categories.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

@implementation NSString (Categories)

+ (NSString *)isStringNull:(NSString *)str
{
    if (str == nil) {
        return @"";
    }

    return str;
}

- (NSString *)urlEncodeUTF8String
{
    if (self) {
        return [self stringByAddingPercentEncodingWithAllowedCharacters:
                    [NSCharacterSet URLQueryAllowedCharacterSet]];
        }

    return nil;
}

+ (NSString *)urlEncodeUTF8String:(NSString *)stringText
{
    if (stringText == nil) {
        return nil;
    }

    NSString *urlStr = [stringText urlEncodeUTF8String];

    return urlStr;
}

- (NSString *)urlDecodeUTF8String
{
    if (self) {
        return [self stringByRemovingPercentEncoding];
    }

    return nil;
}

- (NSURL *)toUrl{
    return [NSURL URLWithString:[self urlEncodeUTF8String]];
}

+ (NSString *)urlDecodeUTF8String:(NSString *)stringText
{
    if (stringText == nil) {
        return nil;
    }

    NSString *urlStr = [stringText urlDecodeUTF8String];

    return urlStr;
}

//字符串 转Unicode

-(NSString *)utf8ToUnicode{

    NSUInteger length = [self length];
    NSMutableString *str = [NSMutableString stringWithCapacity:0];
    for (int i = 0;i < length; i++){
        NSMutableString *s = [NSMutableString stringWithCapacity:0];
        unichar _char = [self characterAtIndex:i];
        // 判断是否为英文和数字
        if (_char <= '9' && _char >='0'){
            [s appendFormat:@"%@",[self substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='a' && _char <= 'z'){
            [s appendFormat:@"%@",[self substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='A' && _char <= 'Z')
            {
            [s appendFormat:@"%@",[self substringWithRange:NSMakeRange(i,1)]];
        }else{
            // 中文和字符
            [s appendFormat:@"\\u%x",[self characterAtIndex:i]];
            // 不足位数补0 否则解码不成功
            if(s.length == 4) {
                [s insertString:@"00" atIndex:2];
            } else if (s.length == 5) {
                [s insertString:@"0" atIndex:2];
            }
        }
        [str appendFormat:@"%@", s];
    }
    return str;

}

//Unicode 转字符串

- (NSString *)replaceUnicode
{
    const char *charString =@"\u94f6\u8272".UTF8String;
    
    NSData *data = [NSData dataWithBytes:charString length:strlen(charString)];
    
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return  string;
}

- (NSString *)slMD5
{
    const char *cStr = [self UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];

    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }

    return result;
}

+ (NSString *)encodeURL:(NSString *)stringText
{
    if (!stringText) {
        return @"";
    }

    NSArray *charSet = [NSArray arrayWithObjects:@"&", @"+", @",", @"/", @":", @";", @"=", @"?", @"@", @" ", @"\t", @"#", @"<", @">", @"\"", @"\n", nil];
    NSArray *codeSet = [NSArray arrayWithObjects:@"%26", @"%2B", @"%2C", @"%2F", @"%3A", @"%3B", @"%3D", @"%3F", @"%40", @"%20", @"%09", @"%23", @"%3C", @"%3E", @"%22", @"%0A", nil];

    NSMutableString *url = [NSMutableString stringWithString:stringText];
    assert([charSet count] == [codeSet count]);

    for (int i = 0; i < [charSet count]; i++) {
        NSRange range = NSMakeRange(0, [url length]);
        [url replaceOccurrencesOfString:[charSet objectAtIndex:i] withString:[codeSet objectAtIndex:i] options:NSCaseInsensitiveSearch range:range];
    }
    
    return [NSString stringWithString:url];
}

- (NSDictionary *)jsonStringToDictionary{
    
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
    
    return dic;
}

- (NSArray *)jsonStringToArray{
    
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
    
    return arr;
}


- (NSURL *)stringToURL{
    
    return [NSURL URLWithString:self];;
}

-(CGSize)stringSizewithFont:(UIFont *)font maxSize:(CGSize)maxSize{
    if (font == nil) {
        return CGSizeZero;
    }
    
    CGSize size = CGSizeZero;
    
    CGRect rect = [self boundingRectWithSize:maxSize options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                  attributes:@{NSFontAttributeName:font} context:nil];
    size = CGSizeMake(rect.size.width, rect.size.height);
    
    return size;
}

- (NSString *)autoLanguage {
    return NSLocalizedString(self, nil);
}

+ (NSString *)getCurrentSystemDateSecond {
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSince1970];
    NSString *strTimeInterval = @(floor(timeInterval)).stringValue;
    
    return strTimeInterval;
}

- (NSString *)stampToDateFormatter:(NSString *)formatter{
    
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateStyle:NSDateFormatterMediumStyle];
    [dateformatter setTimeStyle:NSDateFormatterShortStyle];
    [dateformatter setDateFormat:(formatter)?:@"YYYY-MM-dd HH:mm:ss"];
    NSTimeInterval interval  = self.doubleValue;
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:interval];
    NSString *confromTimespStr = [dateformatter stringFromDate:confromTimesp];
    return confromTimespStr;
}

- (NSString *)YMDHmsToStamp {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:self];
    NSTimeInterval timestamp = [date timeIntervalSince1970];
    return @(timestamp).stringValue;
}

- (NSString *)ac_timeYMDHms {
    
    return [self stampToDateFormatter:@"YYYY-MM-dd HH:mm:ss"];
}

- (NSString *)ac_timeYMDHm {
    
    return [self stampToDateFormatter:@"YYYY-MM-dd HH:mm"];
}

- (NSString *)ac_timeYMDH {
    
    return [self stampToDateFormatter:@"YYYY-MM-dd HH"];
}

- (NSString *)ac_timeYMD {
    
    return [self stampToDateFormatter:@"YYYY-MM-dd"];
}

- (NSString *)ac_timeYM {
    
    return [self stampToDateFormatter:@"YYYY-MM"];
}

- (NSString *)ac_timeY {
    
    return [self stampToDateFormatter:@"YYYY"];
}

- (NSString *)ac_timeMD {
    
    return [self stampToDateFormatter:@"MM-dd"];
}

- (NSString *)ac_timeD {
    
    return [self stampToDateFormatter:@"dd"];
}

- (NSString *)ac_timeHms {
    
    return [self stampToDateFormatter:@"HH:mm:ss"];
}

- (NSString *)ac_timeHm {
    
    return [self stampToDateFormatter:@"HH:mm"];
}

- (NSString *)ac_timeH {
    
    return [self stampToDateFormatter:@"HH"];
}


@end
